/* 封装axios 请求 */
import axios from 'axios'
import { getToken, delToken } from '@/utils/storage'
import { Toast } from 'vant'
import router from '@/router'

/* 新建axios 实例 */
const request = axios.create({
  baseURL: 'http://liufusong.top:8080/',
  timeout: 50000
})

/* 请求拦截器 */
request.interceptors.request.use(config => {
  // console.log(config)
  config.headers.Authorization = `${getToken()}`
  return config
}, error => {
  return Promise.reject(error)
})

/* 响应拦截器 */

request.interceptors.response.use(response => response.data, error => {
  if (error) {
    if (error.response) {
      if (error.response.status === 401) {
        delToken()
        Toast('token失效，请重新登录')
        router.push('/login')
      } else {
        Toast(error.response.data.message)
      }
    }
  }
  return Promise.reject(error)
})

export default request
